<style lang="scss">
#app {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.toolbar {
  height: 60px;
  padding: 10px 20px;
  background: #f5f5f5;
  border-bottom: 1px solid #ddd;
  display: flex;
  align-items: center;
}

.canvas-container {
  flex: 1;
  position: relative;
  overflow: hidden;
}

#logic-flow-container {
  width: 100%;
  height: 100%;
}

.source-node-info {
  margin-bottom: 15px;
  padding: 10px;
  background: #f9f9f9;
  border-radius: 4px;

  p {
    margin: 0;
    color: #666;
  }
}

.dialog-footer {
  text-align: right;
}
</style>

<template>
  <div id="app">
    <div class="toolbar">
      <el-button-group>
        <el-button @click="clearCanvas" icon="el-icon-delete">清空画布</el-button>
        <el-button @click="exportJson" icon="el-icon-download">导出JSON</el-button>
        <el-button @click="importJson" icon="el-icon-upload2">导入JSON</el-button>
        <el-button @click="exportImage" icon="el-icon-picture">导出图片</el-button>
      </el-button-group>
    </div>

    <div class="canvas-container">
      <div id="logic-flow-container" ref="container"></div>
    </div>

    <!-- 新增独立MD节点对话框 -->
    <el-dialog title="新增MD节点" v-model="addNodeDialogVisible" width="600px">
      <el-input v-model="nodePrompt" type="textarea" :rows="4" placeholder="请输入提示词，AI将根据您的输入生成内容"></el-input>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addNodeDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="createMdNode" :loading="aiLoading">生成节点</el-button>
      </div>
    </el-dialog>

    <!-- 基于节点询问AI对话框 -->
    <el-dialog title="询问AI" v-model="askAiDialogVisible" width="600px">
      <div class="source-node-info">
        <p><strong>基于节点：</strong>{{ sourceNodeContent }}</p>
      </div>
      <el-input v-model="aiPrompt" type="textarea" :rows="4" placeholder="请输入您的问题"></el-input>
      <template #footer>
        <el-button @click="askAiDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="askAiAndCreateNode" :loading="aiLoading">询问AI</el-button>
      </template>
    </el-dialog>

    <!-- 导入JSON文件 -->
    <input ref="fileInput" type="file" accept=".json" style="display: none" @change="handleFileImport">

    <!-- ✅ 添加TeleportContainer组件 -->
    <TeleportContainer :flow-id="flowId" />
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import LogicFlow from '@logicflow/core'
import { SelectionSelect, Menu, Snapshot } from '@logicflow/extension'
import '@logicflow/core/dist/index.css';
import '@logicflow/extension/lib/style/index.css'
import { getTeleport, register } from '@logicflow/vue-node-registry'
import { ElMessage, ElMessageBox } from 'element-plus'
import MdNode from './components/MdNode.vue'
import { saveToLocalStorage, loadFromLocalStorage } from './utils/storage.js'
import { callAI } from './utils/ai.js'

// 获取TeleportContainer组件
const TeleportContainer = getTeleport()

// 响应式数据
const lf = ref(null)
const flowId = ref('')
const addNodeDialogVisible = ref(false)
const askAiDialogVisible = ref(false)
const nodePrompt = ref('')
const aiPrompt = ref('')
const sourceNodeId = ref(null)
const sourceNodeContent = ref('')
const contextMenuPosition = ref(null)
const aiLoading = ref(false)
const container = ref(null)
const fileInput = ref(null)

// 调整大小相关状态
const resizeMode = ref(false)
const resizableNodes = ref(new Set())

// 框选相关状态
const selectionSelectEnabled = ref(false)
const exclusiveMode = ref(false)

// 方法定义
const initLogicFlow = () => {
  // 注册插件
  LogicFlow.use(SelectionSelect)
  LogicFlow.use(Menu)
  LogicFlow.use(Snapshot)

  lf.value = new LogicFlow({

    container: container.value,
    width: window.innerWidth,
    height: window.innerHeight - 60,
    grid: {
      size: 20,
      visible: true
    },
    keyboard: {
      enabled: true
    },
    plugins: [
      SelectionSelect, Menu, Snapshot],
    pluginsOptions: {
      selectionSelect: {
        exclusiveMode: true,
      },
    },
    isSilentMode: false,
    stopScrollGraph: false,
    stopZoomGraph: false,
    stopMoveGraph: false,
    allowRotate: true,
    allowResize: true,

  })

  // 注册自定义节点
  console.log('开始注册MD节点...')
  register({
    type: 'md-node',
    component: MdNode,
    effect: ['mdContent', 'width', 'height']
  }, lf.value)
  console.log('MD节点注册完成')
  console.log('LogicFlow实例:', lf.value)
  // console.log('已注册的节点类型:', lf.value.getNodeTypes())

  // 监听graph:rendered事件获取flowId
  lf.value.on('graph:rendered', (_options) => {
    console.log("🚀 ~ initLogicFlow ~ _options:", _options)
  })

  // 初始化flowId
  // flowId.value = `flow-${Date.now()}`

  // 配置右键菜单
  lf.value.extension.menu.addMenuConfig({
    nodeMenu: [
      {
        text: '新增独立MD节点',
        callback: (node) => {
          showAddNodeDialog()
        }
      },
      {
        text: '继续询问',
        callback: (node) => {
          showAskAiDialog(node)
        }
      },

    ],
    graphMenu: [
      {
        text: '新增独立MD节点',
        callback: (position) => {
          contextMenuPosition.value = position
          showAddNodeDialog()
        }
      }
    ]
  })


  //开启  reszie
  // const selectionSelect = lf?.value.extension?.selectionSelect;
  // selectionSelect?.openSelectionSelect?.();
  // lf?.value?.openSelectionSelect();
  // lf.value.setSelectionSelectMode(true)
  lf?.value?.extension.selectionSelect.setSelectionSense(false, true);


  // 监听数据变化，自动保存
  lf.value.on('history:change', () => {
    saveData()
  })

  // 监听节点双击事件
  lf.value.on('node:dblclick',(e)=>{
  debugger
    
  })

  // 监听键盘事件
  lf.value.on('node:keydown', ({ data, e }) => {
    if (e.ctrlKey && e.key === 'Enter' && data.type === 'md-node') {
      lf.value.setProperties(data.id, {
        ...data.properties,
        isEditing: false
      })
    }
  })
}

const showAddNodeDialog = () => {
  nodePrompt.value = ''
  addNodeDialogVisible.value = true
}

const showAskAiDialog = (node) => {
  sourceNodeId.value = node.id
  sourceNodeContent.value = node.properties?.mdContent || node.text || ''
  aiPrompt.value = ''
  askAiDialogVisible.value = true
}

const createMdNode = async () => {
  if (!nodePrompt.value.trim()) {
    ElMessage.warning('请输入提示词')
    return
  }

  aiLoading.value = true
  try {
    const aiResponse = await callAI(nodePrompt.value)

    const nodeId = `md-node-${Date.now()}`
    const position = contextMenuPosition.value && contextMenuPosition.value.x ? contextMenuPosition.value : { x: 200, y: 200 }

    lf.value.addNode({
      id: nodeId,
      type: 'md-node',
      x: position.x,
      y: position.y,
      properties: {
        title: nodePrompt.value?.substring(0, 50) + '...',
        mdContent: aiResponse,
        width: 200,
        height: 150
      }
    })

    addNodeDialogVisible.value = false
    ElMessage.success('节点创建成功')
  } catch (error) {
    ElMessage.error('AI调用失败：' + error.message)
  } finally {
    aiLoading.value = false
  }
}

const askAiAndCreateNode = async () => {
  if (!aiPrompt.value.trim()) {
    ElMessage.warning('请输入问题')
    return
  }

  aiLoading.value = true
  try {
    const fullPrompt = `基于以下内容：\n${sourceNodeContent.value}\n\n问题：${aiPrompt.value}`
    const aiResponse = await callAI(fullPrompt)

    const sourceNode = lf.value.getNodeModelById(sourceNodeId.value)
    const targetNodeId = `md-node-${Date.now()}`

    // 在源节点右边创建目标节点
    const targetX = sourceNode.x + 300
    const targetY = sourceNode.y

    lf.value.addNode({
      id: targetNodeId,
      type: 'md-node',
      x: targetX,
      y: targetY,
      properties: {
        title: aiPrompt.value?.substring(0, 50) + '...',
        mdContent: aiResponse,
        width: 200,
        height: 150
      }
    })

    // 连接两个节点
    lf.value.addEdge({
      sourceNodeId: sourceNodeId.value,
      targetNodeId: targetNodeId,
      type: 'polyline'
    })

    askAiDialogVisible.value = false
    ElMessage.success('AI回答节点创建成功')
  } catch (error) {
    ElMessage.error('AI调用失败：' + error.message)
  } finally {
    aiLoading.value = false
  }
}

const clearCanvas = () => {
  ElMessageBox.confirm('确定要清空画布吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    lf.value.clearData()
    localStorage.removeItem('logicflow-data')
    ElMessage.success('画布已清空')
  })
}

const exportJson = () => {
  const data = lf.value.getGraphData()
  const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `logicflow-${Date.now()}.json`
  a.click()
  URL.revokeObjectURL(url)
  ElMessage.success('JSON导出成功')
}

const importJson = () => {
  fileInput.value.click()
}

const handleFileImport = (event) => {
  const file = event.target.files[0]
  if (!file) return

  const reader = new FileReader()
  reader.onload = (e) => {
    try {
      const data = JSON.parse(e.target.result)
      lf.value.render(data)
      ElMessage.success('JSON导入成功')
    } catch (error) {
      ElMessage.error('JSON格式错误')
    }
  }
  reader.readAsText(file)
}

const exportImage = () => {
  lf.value.getSnapshot().then((data) => {
    const a = document.createElement('a')
    a.href = data
    a.download = `logicflow-${Date.now()}.png`
    a.click()
    ElMessage.success('图片导出成功')
  })
}

const saveData = () => {
  const data = lf.value.getGraphData()
  saveToLocalStorage('logicflow-data', data)
}

// 调整大小控制函数
const enableNodeResize = (node) => {
  resizableNodes.value.add(node.id)
  // 更新节点属性，触发MdNode组件重新渲染
  lf.value.setProperties(node.id, {
    ...node.properties,
    resizable: true
  })
  ElMessage.success('节点调整大小已开启')
}

const disableNodeResize = (node) => {
  resizableNodes.value.delete(node.id)
  lf.value.setProperties(node.id, {
    ...node.properties,
    resizable: false
  })
  ElMessage.success('节点调整大小已关闭')
}

// 开启框选功能
const openSelectionSelect = () => {
  lf.value.openSelectionSelect()
  selectionSelectEnabled.value = true
  ElMessage.success('框选功能已开启')
}

// 关闭框选功能
const closeSelectionSelect = () => {
  lf.value.closeSelectionSelect()
  selectionSelectEnabled.value = false
  ElMessage.success('框选功能已关闭')
}

// 切换独占模式
const toggleExclusiveMode = () => {
  exclusiveMode.value = !exclusiveMode.value
  // 重新配置插件
  lf.value.setPluginOptions('SelectionSelect', {
    exclusiveMode: exclusiveMode.value
  })
  ElMessage.success(`独占模式已${exclusiveMode.value ? '开启' : '关闭'}`)
}

const loadData = () => {
  const data = loadFromLocalStorage('logicflow-data')
  console.log("🚀 ~ loadData ~ data:", data)
  if (data) {
    console.log('开始渲染数据:', data)
    lf.value.render(data)
    console.log('数据渲染完成')

    // 检查是否有md-node节点
    const mdNodes = data.nodes?.filter(node => node.type === 'md-node')
    console.log('MD节点数量:', mdNodes?.length || 0)
    if (mdNodes && mdNodes.length > 0) {
      console.log('MD节点详情:', mdNodes)
    }
  } else {
    // 没有数据时创建默认的【开始】节点
    const defaultData = {
      nodes: [
        {
          id: 'start-node-1',
          type: 'circle',
          x: 300,
          y: 200,
          text: '开始',
          properties: {
            width: 80,
            height: 80
          }
        }
      ],
      edges: []
    }
    lf.value.render(defaultData)
    // 保存默认数据到本地存储
    saveData()
  }
}
// 组件挂载时初始化
onMounted(() => {
  nextTick(() => {
    initLogicFlow()
    loadData()
  })
})
</script>
